package com.bw.car.view

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.MotionEvent
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.bw.base.constants.RoutePath
import com.bw.car.R
import com.bw.car.adapter.CarCodeAdapter
import com.bw.car.databinding.ActivityUpdateCarBinding
import com.bw.car.entity.AddCarParam
import com.bw.car.inter.Click
import com.bw.car.net.CarViewModel
import com.bw.common.view.BaseMvvmActivity
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

@Route(path = RoutePath.PATH_UPDATE_CAR)
class UpdateCarActivity : BaseMvvmActivity<ActivityUpdateCarBinding,CarViewModel>() {

    private lateinit var cameraLauncher: ActivityResultLauncher<Intent>

    private lateinit var permissionLauncher: ActivityResultLauncher<Array<String>>

    private lateinit var currentPhotoPath: String

    private var carMode:String=""

    private val requiredPermissions = arrayOf(
        Manifest.permission.CAMERA,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )

    private val list:MutableList<String> = mutableListOf(
        "京","津","冀","晋","鲁","吉","粤","沪","蒙","川","辽","闽","苏","宁","青","黑","豫","皖","浙","藏"
    )

    private val carCodeAdapter : CarCodeAdapter= CarCodeAdapter(list)
    override fun initView() {
        binding.topBar.tvTitle.text = "添加车辆"
        binding.topBar.ivBack.setOnClickListener { finish() }
        binding.topBar.ivAdd.visibility = View.GONE


        binding.rv.layoutManager=GridLayoutManager(this,5)
        binding.rv.adapter=carCodeAdapter


        carCodeAdapter.setItemClick(object :Click<String>{
            override fun onCLick(item: String, position: Int) {
                binding.carStyle.text=item
            }
        })

        binding.carCode.addTextChangedListener {
            carMode="${binding.carStyle.text}${it}"
        }


        cameraLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
            if(it.resultCode == RESULT_OK){
                val bitmap=BitmapFactory.decodeFile(currentPhotoPath)
            }
        }

        permissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()){ it ->
            if(it.all {per-> per.value }){
                openCamera()
            }
        }


        binding.add.setOnClickListener {
            if(carMode.length<3){
                ToastUtils.showShort("请输入正确车牌号")
            }else{

                vm.addCar(AddCarParam(
                    licensePlate = carMode,
                    provinceAbbreviation = binding.carStyle.text.toString(),
                    userId = 1
                ))
            }
        }


        binding.open.setOnClickListener {


            val isYes=requiredPermissions.all {
                    ContextCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED
                }
            if(isYes){
                openCamera()
            } else {
                permissionLauncher.launch(requiredPermissions)
            }

        }




    }

    override fun initData() {
        carCodeAdapter.notifyDataSetChanged()

        vm.addCarSuccess.observe(this){
            if(null!=it.provinceAbbreviation) ARouter.getInstance().build(RoutePath.PATH_CAR_PAY).withString(
                "carCode",carMode
            ).navigation()
        }
    }

    @SuppressLint("SuspiciousIndentation")
    private fun openCamera(){
      val intent=Intent(MediaStore.ACTION_IMAGE_CAPTURE)

        if(null!=intent.resolveActivity(packageManager)){
            val file:File?=createImageFile()
            file?.also {
                val uri :Uri = FileProvider.getUriForFile(
                    this,
                    "${applicationContext.packageName}.fileprovider",
                    it
                )
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
                //拉起相机
                cameraLauncher.launch(intent)
            }

        }
    }

    private fun createImageFile():File?{
        val time=SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date())
        val storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        if (storageDir == null) {
            Log.e("Camera", "外部存储目录不可用")
            return null
        }
        return File.createTempFile("JPEG_${time}",".jpg",storageDir).apply {
            currentPhotoPath=absolutePath
        }
    }
}